package com.wdb007.venus.wss.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.facade.BookgridService;
import com.wdb007.venus.svc.facade.ProcessInstructionService;
import com.wdb007.venus.svc.facade.process.model.ProcessInstructionLogDTO;
import com.wdb007.venus.wss.channelgroup.BookCaseChannelGroups;
import com.wdb007.venus.wss.constants.PushActionEnum;
import com.wdb007.venus.wss.constants.WsAPPEnum;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;

@Service("bookGridUnlockResService")
@Sharable
@Scope("prototype")
public class BookGridUnlockResService implements WebSocketServerService {

	private static Logger logger = LoggerFactory.getLogger(BookGridUnlockResService.class);
	
	@Autowired
	private BookgridService bookgridService;
	
	@Autowired
	private ProcessInstructionService processInstructionService;
	
	@Resource(name="appService")
	private WebSocketServerService appService;
	
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		
		JSONObject jsonObj = JSON.parseObject(request);
		String bookGridId = jsonObj.getString("bookGridId");
		String bookCaseId = bookGridId.substring(0, 10);
		logger.info("debug {} : 书柜[{}]书格[{}],响应内容[{}]", jsonObj.getString("action"), bookCaseId,bookGridId,jsonObj.toJSONString());
		Integer status = Integer.valueOf(jsonObj.get("status")+"");
		//如果status为负数，则说明开门失败，直接将该门的状态改为2，打开失败
		String pushId = jsonObj.getString("pushId");
		ProcessInstructionLogDTO pi = new ProcessInstructionLogDTO();
		pi.setBookgridCode(bookGridId);
		pi.setDoorStatus(status);
		pi.setInstructionGroupId(Long.valueOf(pushId));
		pi.setContent(jsonObj.toJSONString());
		pushId = processInstructionService.unlockRes(pi) + "";
		if(1 > status) {
			String userId = bookgridService.unlockFailed(bookGridId);
			JSONObject jsonApp = new JSONObject();
			jsonApp.put("action", WsAPPEnum.unlock_failed.name());
			jsonApp.put("userid", userId);
			jsonApp.put("bookgrid_code", bookGridId);
			appService.doService(ctx, jsonApp.toJSONString());
			return null;
		}
		jsonObj.put("action", PushActionEnum.bookgrid_status_req.name());
		jsonObj.remove("status");
		pi.setContent(jsonObj.toJSONString());
		processInstructionService.statusReq(pi);
		logger.info("debug {} : 书柜[{}]书格[{}],broadcast内容[{}]", jsonObj.getString("action"), bookCaseId,bookGridId,jsonObj.toJSONString());
		BookCaseChannelGroups.broadcast(bookCaseId, jsonObj.toJSONString());
		
		return null;
	}

}
